package com.byit.controller;


import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.byit.constant.DefaultValue;
import com.byit.domain.AppKeywords;
import com.byit.domain.vo.DictVo;
import com.byit.enums.PromptInfo;
import com.byit.log.ChannelType;
import com.byit.log.Log;
import com.byit.log.OperatorType;
import com.byit.msg.MessageResult;
import com.byit.service.IAppKeywordsService;
import com.byit.service.ISysDictService;
import com.byit.shrio.session.SessionHelper;
import com.byit.utils.StringUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpSession;
import java.util.Date;
import java.util.HashMap;
import java.util.List;

/**
 * keywords 前端控制器
 *
 * @author tjm
 * @date 2019年1月2日
 */
@RestController
@RequestMapping("/api/sys/keywords")
public class AppKeywordsController {

    private Logger logger = LoggerFactory.getLogger(this.getClass());

    @Autowired
    private IAppKeywordsService appKeywordsService;
    @Autowired
    private ISysDictService sysDictService;

    /**
     * 添加
     */
    @Log(title = "关键字", operate = OperatorType.DATA_INSERT, channel = ChannelType.WEB_INTER)
    @PostMapping("/add")
    public Object add( @RequestParam("keyword") String keyword,
                       @RequestParam("byOrder") Integer byOrder) {
        try {
            AppKeywords keywords = new AppKeywords();
            keywords.setKeyword(keyword);
            keywords.setType("0");
            keywords.setSeat("0");
            if (1 > byOrder && 99 < byOrder){
                return MessageResult.error("排序请传1~99之间的整数");
            }else {
                keywords.setByOrder(byOrder);
            }
            keywords.setSource("1");
            keywords.setCreateTime(new Date());
            keywords.setUpdateTime(keywords.getCreateTime());
            appKeywordsService.insert(keywords);
            return MessageResult.success();
        } catch (Exception e) {
            e.printStackTrace();
            logger.error(e.getMessage());
            return MessageResult.error(e);
        }
    }

    /**
     * 修改
     */
    @Log(title = "关键字", operate = OperatorType.DATA_UPDATE, channel = ChannelType.WEB_INTER)
    @PostMapping("/update")
    public Object update(@RequestParam("id") Long id,
                         String keyword,
                         Integer byOrder) {
        try {
            AppKeywords keywords = new AppKeywords();
            keywords.setId(id);
            if (StringUtil.isNotEmpty(keyword)){
                keywords.setKeyword(keyword);
            }
            if (null != byOrder){
                if (1 > byOrder && 99 < byOrder){
                    return MessageResult.error("排序请传1~99之间的整数");
                }else {
                    keywords.setByOrder(byOrder);
                }
            }
            keywords.setUpdateTime(new Date());
            appKeywordsService.updateById(keywords);
            return MessageResult.success();
        } catch (Exception e) {
            e.printStackTrace();
            logger.error(e.getMessage());
            return MessageResult.error(e);
        }
    }

    /**
     * 详情
     */
    @Log(title = "关键字", operate = OperatorType.DATA_SELECT, channel = ChannelType.WEB_INTER)
    @PostMapping("/details")
    public Object details(@RequestParam("id") Long id) {
        AppKeywords appKeywords = appKeywordsService.selectById(id);
        if (appKeywords.getIsDel()==1){
            return MessageResult.error("该数据已删除");
        }
        return MessageResult.success(appKeywords);
    }

    /**
     * 分页列表查询
     */
    @Log(title = "关键字", operate = OperatorType.DATA_SELECT, channel = ChannelType.WEB_INTER)
    @GetMapping("/list")
    public Object list(AppKeywords keywords,
                       @RequestParam(value = "page", defaultValue = DefaultValue.PAGE_FIRST) int page,
                       @RequestParam(value = "limit", defaultValue = DefaultValue.PAGE_SIZE) int limit) {
        Page<AppKeywords> pageInfo = new Page<>(page, limit);
        EntityWrapper<AppKeywords> wrapper = new EntityWrapper<>();
        wrapper.setSqlSelect("id,keyword,type,seat,source,by_order as byOrder,search_num as searchNum");
        wrapper.eq("is_del",0);
        if (StringUtil.isNotNull(keywords.getKeyword())){
            wrapper.like("keyword",keywords.getKeyword());
        }
        if (StringUtil.isNotEmpty(keywords.getSeat())){
            wrapper.eq("seat",keywords.getSeat());
        }
        if (StringUtil.isNotEmpty(keywords.getSource())){
            wrapper.eq("source",keywords.getSource());
        }
        if (StringUtil.isNotEmpty(keywords.getType())){
            wrapper.eq("type",keywords.getType());
        }
        wrapper.orderBy("by_order");
        wrapper.orderBy("update_time",false);

        Page<AppKeywords> list = appKeywordsService.selectPage(pageInfo, wrapper);
        return MessageResult.warpper(PromptInfo.SYS_SECCUSS, list);
    }

    /**
     * 逻辑删除
     */
    @Log(title = "关键字", operate = OperatorType.DATA_DELETE, channel = ChannelType.WEB_INTER)
    @PostMapping("/del")
    public Object delete(HttpSession session, @RequestParam("ids") String ids) {
        Long userId = SessionHelper.getUserId(session);
        List<Long> idList = StringUtil.splitLong(ids, ",");
        for (Long id : idList) {
            AppKeywords keywords = new AppKeywords();
            keywords.setId(id);
            keywords.setIsDel(1);
            keywords.setOperationId(userId);
            keywords.setUpdateTime(new Date());
            appKeywordsService.updateById(keywords);
        }
        return MessageResult.success();
    }

    /**
     * 获取码表数据
     */
    @Log(title = "关键字", operate = OperatorType.DATA_SELECT, channel = ChannelType.WEB_INTER)
    @GetMapping("/getCode")
    public Object getCode() {
        List<DictVo> keywordType = sysDictService.selectDictByType("keywordType");
        List<DictVo> keywordSource = sysDictService.selectDictByType("keywordSource");
        List<DictVo> keywordSeat = sysDictService.selectDictByType("keywordSeat");
        HashMap<String,List<DictVo>> data = new HashMap<>();
        data.put("type",keywordType);
        data.put("source",keywordSource);
        data.put("seat",keywordSeat);
        return MessageResult.success(data);
    }
}
